/*
 * Copyright© 2013-2018 YZTC 
 * Author zhenghl 
 * 本公司保留所有下述内容的权利; 
 * 本内容为保密信息，仅限本公司内部使用; 
 * 非经本公司书面许可，任何人不得外泄或用于其他目的; 
*/
package com.wxmp.core.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.wxmp.core.util.SessionUtil;
/**
 * 用户拦截器
 * @author  hermit
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
	private final static Logger log= Logger.getLogger(AuthInterceptor.class);
    private AntPathMatcher matcher = new AntPathMatcher();
	public String[] allowUrls;// 也可以注解
	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}
	
    private boolean matchAllowUrls(String uri){ 
        boolean result = false;
        if(this.allowUrls==null || this.allowUrls.length==0)
            return result;
        for (String pattern : this.allowUrls) {
            if (matcher.match(pattern, uri)) { 
                result = true;
                break;
            }
        }
        return result;
    }
    
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
		if (null != allowUrls && allowUrls.length >= 1)
			for (String url : allowUrls) {
				if (requestUrl.contains(".svg") || requestUrl.contains(".ttf") || requestUrl.contains(".woff") || requestUrl.contains(".eot") || requestUrl.contains(".css") || requestUrl.contains(".js") || requestUrl.contains(".png") || requestUrl.contains(".jpg") || requestUrl.contains("/message") || requestUrl.equals(url) || matchAllowUrls(url)) {
					return true;
				}
			}
		if (SessionUtil.getUser() != null) {
			SessionUtil.session.setMaxInactiveInterval(60 * 60 * 30);
		}
		if(null==SessionUtil.getUser()){
			if (isAjaxRequest(request)) {
				response.setStatus(300);
				response.setHeader("sessionState", "notLogin");
			} else {
				response.sendRedirect("/views/login.html");
			}
			return false;
		}
		return super.preHandle(request, response, handler);
	}
	public static boolean isAjaxRequest(HttpServletRequest request) {
		boolean isAjax = request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest");
		return isAjax;
	}
}
